package com.itheima.leadnews.search.service.Impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.pojo.ApUserSearch;
import com.heima.utils.common.ThreadLocalUtils;
import com.itheima.leadnews.search.service.ApUserSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存搜索历史
     *
     * @param apUserSearch
     */
    @Override
    public void saveApUserSearch(ApUserSearch apUserSearch) {
        Query query = Query.query(Criteria.where("keyword").is(apUserSearch.getKeyword()).and("userId").is(apUserSearch.getUserId()));
        ApUserSearch userSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        //判断用户是否已经保存了搜索历史,如果存在则更新时间
        if (userSearch == null) {
            //不存在,保存关键字
            mongoTemplate.save(apUserSearch);
        } else {
            //已经存在,更新时间
            userSearch.setCreatedTime(new Date());
            //已存在_id,全量更新
            mongoTemplate.save(userSearch);
        }
    }

    /**
     * 搜索历史展示
     *
     * @param pageSize
     * @return
     */
    @Override
    public ResponseResult load(Integer pageSize) {
        //查询该用户的搜索关键字
        Query query = Query.query(Criteria.where("userId").is(ThreadLocalUtils.getUserId()));
        //排序
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        //分页展示,只展示最新的N个
        query.limit(pageSize);
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }

    /**
     * 删除搜索关键字
     * @param id
     * @return
     */
    @Override
    public ResponseResult del(String id) {
        Query query = Query.query(Criteria.where("_id").is(id));
        mongoTemplate.remove(query,ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
